package top.codechap.ioc.framework.beans;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 用来存储和管理多个PropertyValue
 */
public class MutablePropertyValues implements Iterable<PropertyValue>{

    //定义list集合对象,用来存储PropertyValue对象
    private final List<PropertyValue> propertyValueList;    //使用final修饰的属性,必须在构造器里面或之前进行赋值

    public MutablePropertyValues() {
        this.propertyValueList = new ArrayList<>();
    }

    public MutablePropertyValues(List<PropertyValue> propertyValueList) {
        if (propertyValueList == null) {
            this.propertyValueList = new ArrayList<>();
        } else {
            this.propertyValueList = propertyValueList;
        }
    }

    //获取所有的PropertyValue对象,以数组的形式返回
    public PropertyValue[] getPropertyValues() {
        //直接将集合转换为数组并返回
        return propertyValueList.toArray(new PropertyValue[0]);
    }

    //根据PropertyValue的name属性值,获取PropertyValue对象
    public PropertyValue getPropertyValue(String propertyName) {
        for (PropertyValue propertyValue : propertyValueList) {
            if (propertyName.equals(propertyValue.getName())) {
                return propertyValue;
            }
        }
        return null;
    }

    //判断集合是否为空
    public boolean isEmpty() {
        return propertyValueList.isEmpty();
    }

    //添加PropertyValue对象
    public MutablePropertyValues addPropertyValue(PropertyValue propertyValue) {
        //判断集合中存储的propertyValue对象是否和传进来的重复,如果重复,则直接覆盖
        for (int i = 0; i < propertyValueList.size(); i++) {
            //获取集合中每一个PropertyValue对象
            PropertyValue currentPV = propertyValueList.get(i);
            if (currentPV.getName().equals(propertyValue.getName())) {
                propertyValueList.set(i,propertyValue);
                return this;    //返回MutablePropertyValues,实现链式编程
            }
        }
        propertyValueList.add(propertyValue);
        return this;    //返回MutablePropertyValues,实现链式编程
    }

    //判断是否有指定name属性值的对象
    public boolean contains(String propertyName) {
        return getPropertyValue(propertyName) != null;
    }

    //获取迭代器对象
    @Override
    public Iterator<PropertyValue> iterator() {
        return propertyValueList.listIterator();
    }
}
